const mysql = require('../../core/mysql');

const log = require('../../core/logger').getLogger("system");
const moment = require('moment');
const common = require('../../core/common');
const stringUtils = require('../../core/util/StringUtils');
const _ = require('lodash');

exports.add = async(ctx) => {
    let vendor_name = ctx.request.body.vendor_name ? ctx.request.body.vendor_name.trim() : '';
    let note = ctx.request.body.note || '';
    if (vendor_name === '') {
        ctx.body = {
            result: 201,
            message: "请检查参数"
        };
        return;
    }
    let newVendor = {
        vendor_name,
        note
    };
    try{
        let selectExistVendor = await mysql.query(`select * from vendor where vendor_name = ? `, vendor_name);
        if (selectExistVendor.length > 0){
            ctx.body = {
                result: 202,
                message: "已存在此供应商"
            };
            return;
        }
        let ret = await mysql.query(`INSERT INTO vendor SET ?`, newVendor);
        if (!ret || ret.insertId === -1){
            ctx.body = {
                result: 203,
                message: "新增供应商失败"
            };
        } else {
            ctx.body = {
                result: 200,
                id: ret.insertId,
                message: "新增供应商成功"
            };
        }
    }catch (e) {
        ctx.body = {
            result: 205,
            message: "新增供应商失败"+e.toString()
        };
    }
}

exports.delete = async(ctx) => {
    let vendor_id = ctx.params.vendor_id || 0;
    if (vendor_id <= 0) {
        ctx.body = {
            result: 201,
            message: "请检查参数"
        };
        return
    }
    try{
        let selectProducts = await mysql.query(`select COUNT(product_id) AS Total from product WHERE vendor_id = ? and is_deleted = 0 `, vendor_id);
        if (selectProducts[0].Total > 0){
            ctx.body = {
                result: 203,
                message: "删除失败,存在该厂商设备"
            };
            return
        }
        ret = await mysql.query(`delete from vendor WHERE vendor_id = ?`, vendor_id);
        if (!ret || ret.affectedRows === 0){
            ctx.body = {
                result: 202,
                message: "对象不存在或已删除"
            };
        } else {
            ctx.body = {
                result: 200,
                message: "删除成功"
            };
        }
    }catch (e) {
        ctx.body = {
            result: 205,
            message: "错误"+e.toString()
        };
    }
}

exports.update = async(ctx) => {
    let vendor_id = ctx.request.body.vendor_id || 0;
    let vendor_name = ctx.request.body.vendor_name ? ctx.request.body.vendor_name.trim() : '';
    let note = ctx.request.body.note || '';

    if (vendor_id <= 0 || vendor_name === '') {
        ctx.body = {
            result: 201,
            message: "请检查参数"
        };
    }else{
        try {
            let selectRows = await mysql.query(`SELECT * FROM vendor WHERE vendor_id = ?`, vendor_id);
            if (selectRows.length > 0) {
                let selectExistVendor = await mysql.query(`select * from vendor where vendor_name = ? and vendor_id <> ? `, [vendor_name,vendor_id]);
                if (selectExistVendor.length > 0){
                    ctx.body = {
                        result: 202,
                        message: "已存在此供应商"
                    };
                    return;
                }
                selectRows[0].vendor_name = vendor_name;
                selectRows[0].note = note;
                ret = await mysql.query(`UPDATE vendor SET ? WHERE vendor_id= ? `, [selectRows[0],vendor_id]);
                if (!ret || ret.insertId === -1) {
                    ctx.body = {
                        result: 204,
                        message: "更新失败"
                    };
                } else {
                    ctx.body = {
                        result: 200,
                        message: "更新成功"
                    };
                }
            } else {
                ctx.body = {
                    result: 203,
                    message: "对象不存在或者已删除"
                };
            }
        }catch (e) {
            ctx.body = {
                result: 205,
                message: "更新失败"+e.toString()
            };
        }
    }
}

exports.getList = async(ctx) => {
    let create_user_id = ctx.user.id || '';
    let keyword = ctx.query.keyword ? ctx.query.keyword.trim() : '';
    let counts = ctx.query.counts || 10;
    let indexfrom = ctx.query.indexfrom || 0;

    if (create_user_id === ''){
        ctx.body = {
            result: 201,
            message: "无效的用户id"
        };
    } else {
        try {
            let results = (keyword === '') ? await mysql.query(`SELECT * FROM vendor ORDER BY vendor_id LIMIT ${indexfrom}, ${counts} ` )
                : await mysql.query(`SELECT * FROM vendor WHERE vendor_name like '%${keyword}%' ORDER BY vendor_id LIMIT ${indexfrom}, ${counts} ` );
            let totalResult = (keyword === '') ? await mysql.query(`SELECT COUNT(vendor_id) AS total FROM vendor `)
                : await mysql.query(`SELECT COUNT(vendor_id) AS total FROM vendor WHERE vendor_name like '%${keyword}%' `);
            ctx.body = {
                result: 200,
                list:results,
                totalpage:Math.ceil((totalResult.length > 0 ? totalResult[0].total : 0)/counts),
                totalcounts:totalResult.length > 0 ? totalResult[0].total : 0,
                message: "查询成功"
            };
        }catch (e) {
            ctx.body = {
                result: 205,
                message: "错误 " + e.toString()
            };
        }
    }
}